from flask import Flask, request, jsonify
from face_recognition_service import get_face_encoding, get_recognize_face

app = Flask(__name__)

# 提取人脸特征，并进行128维编码
@app.route('/face_encoding', methods = ['POST'])
def face_encoding():
    # 获取上传的图片文件
    image = request.files['image']
    if not image:
        # 如果没有提供图片文件，返回错误信息
        return jsonify({'error': 'No image file provided'}), 400

    try:
        # 调用get_face_encoding函数获取特征编码
        face_encoding_list = get_face_encoding(image)
        if not face_encoding_list:
            # 如果没有检测到人脸，返回错误信息
            return jsonify({'error': 'No face detected in the image'}), 404
        # 返回特征编码
        return jsonify({'face_encoding': face_encoding_list})
    except Exception as e:
        # 处理其他可能的异常
        return jsonify({'error': str(e)}), 500
    

# 识别人脸并返回识别结果
@app.route('/recognize_face', methods = ['POST'])
def recognize_face():
    if 'image' not in request.files or 'data' not in request.form:
        return jsonify({"error": "Missing image file or JSON data"}), 400

    image_file_stream = request.files['image'].stream
    json_data = request.form['data']

    recognition_result = get_recognize_face(image_file_stream, json_data)

    if recognition_result:
        return jsonify({"recognized_id": recognition_result})
    else:
        return jsonify({"error": "No face recognized or no match found"}), 404
